import { useUserStore } from '@/store/modules/user.js';
import { transformToUrl } from '@/commonUtils/globalFun.js';

let baseURL = 'http://127.0.0.1:8080';

(async()=>{
	const res = await wx.getSystemInfo();
	if (res.brand !== "devtools") baseURL = "http://192.168.31.247:8080";
	else baseURL = "http://127.0.0.1:8080"
})()

// 添加拦截器

const pathNoToken = ['/login'];
const httpInterceptor = {
	// 拦截前触发
 	 invoke(options) {

		if (options.url !== "/upload") {
			options.timeout = 30000;
		}
		else {
			options.timeout = 1000 * 60 * 30;
		}
		// 非http开头的
		const noAddToken = !pathNoToken.some((item) => item == options.url);
		if (!options.url.startsWith('http')) {
				options.url = baseURL + options.url;
		
		}

		if (options.method == 'get' && options.data) {
			options.url += transformToUrl(options.data);
		}
		// 请求超时ms


		options.header = {
			...options.header,
			'source-client': 'miniapp',
		};
		// 添加token
		const { jwt } = useUserStore();
		if (jwt && noAddToken) {
			options.header.Authorization = jwt;
		}
	},

};
uni.addInterceptor('request', httpInterceptor);
uni.addInterceptor('uploadFile', httpInterceptor);

const http = (options) => {
	return new Promise((resolve, reject) => {
		uni.request({
			...options,
			// 响应成功
			success(res) {
				if (res.statusCode >= 200 && res.statusCode < 300 && res.data?.code == 1) {
					resolve(res.data);
				} else if (res.data?.code === 0 && res.data?.msg === 'NOT_LOGIN') {
					uni.showToast({
						title: '暂未登录',
						icon: 'none',
						mask: true
					});
					setTimeout(() => {
						uni.reLaunch({
							url: "/pages/login/login"
						});
					}, 1000);
				} else {
					reject(res.data.msg);
				}
			},
			fail(err) {
				uni.showToast({
					icon: 'none',
					title: '网络错误',
				});
				reject(err);
			},
		});
	});
};
const uploadFile = (config, onProgress = () => { }) => {
	return new Promise((resolve, reject) => {
		const uploadTask = uni.uploadFile({
			url: '/upload',  //仅为示例，非真实的接口地址
			filePath: config.filePath,
			name: config.name || (Date.now() + ""),
			formData: config.formData || {
				'user': 'test'
			},

			success: (res) => {
				resolve(JSON.parse(res.data));
			},
			fail(err) {
				reject(err);
			}
		});
		uploadTask.onProgressUpdate((res => {
			onProgress(res);
		}));
	});
};



export {
	http,
	uploadFile
};
